<template>
  <div id="barChart" ref="echarts" style="width: 100%;height:100%; margin: auto;"></div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  data() {
    return {}
  },
  props: {
    chartData: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  watch: {
    chartData: {
      deep: true,
      handler() {
        this.initChart();
      },
    },
  },
  mounted() {
    // this.$nextTick(() => { 
      this.initChart();
    // });
  },
  methods: {
    initChart() {
      let myChart = echarts.getInstanceByDom(document.getElementById("barChart"));
      if (myChart == null) {
        myChart = echarts.init(this.$refs.echarts);
      }
      // var myChart = echarts.init(this.$refs.echarts);
      window.addEventListener("resize", function () {
        this.myChart.resize();
      });
      var option = {
        title: {
          text: this.chartData.chartTitle,
          left: 'center',
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        grid: {
          left: "5%",
          right: "5%",
          bottom: "5%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: this.chartData.xData,
          axisLine: { show: false },
          axisTick: { show: false },
          splitLine: { show: false },
        },
        yAxis: {
          type: "value",
          axisLine: { show: false },
          axisTick: { show: false },
          splitLine: { show: false },
          axisLabel: { show: false },
        },
        series: [
          {
            type: "bar",
            data: this.chartData.yData,
            barWidth: 15,
            itemStyle: {
              borderRadius: 10,
              color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                { offset: 0, color: "#37BBF8" },
                { offset: 1, color: "#3977E6" },
              ]),
            },
          },
        ],
      };
      myChart.setOption(option,true);
      console.log(option.xAxis.data);
    },
    beforeDestroy() {
      //在组件生命周期结束的时候销毁，removeEventListener和addEventListener中对应的参数要一致。
      window.removeEventListener("resize", function () {
        this.myChart.resize();
      });
    },
  },
}
</script>

<style></style>

